/**
 * Created by DevilsEyes on 2016/3/14.
 * productDetail
 */
'use strict';

define(['text!path/productDetail/tmp.html?' + cacheControl,
    'logger', 'layer', 'anime', 'timer', 'iscroll'], function (page, logger, layer, anime, timer) {

    //参数转为字符串key
    var params2key = function (rankStr, options) {
        return rankStr.replace(/>([^>]+)?/g, function (str, key, origin) {
            return '>' + options[key];
        });
    };

    //定义SpecsManager
    function Constructor_SpecsManager() {
        console.dir(this);

        //策略规格表
        this.StrategyMap = {};
        //============= StrategyMap ================
        // @key: _id
        //
        //      _id         String      Spec_Id
        //      strategy    Number      策略标识
        //      name        Number      规格名称
        //      map         Map         分组列表
        //      all         Map         全部列表
        //
        //------------------------------------------

        //普通规格表
        this.SpecMap = {};
        //=============== SpecMap ==================
        // @key: _id
        //
        //      _id         String      Spec_Id
        //      name        Number      规格名称
        //      map         Map         Specs列表
        //
        //------------------------------------------

        //规格权重
        this.rank = '';
        //================= rank ===================
        //
        //      String      'Spec_IdA>Spec_IdB>Spec_IdC'
        //
        //------------------------------------------

        //存储空间
        this.data = {};
        //  "SpecVA>SpecVB>SpecVC" : "SKU_ID"

        //方法 - 按维度查询SKUid
        this.getSKUid = function (options) {
            var sku_id = this.data[params2key(this.rank, options)];
            return sku_id && sku_id.id || null;
        };

        //获取策略规格中的一级分类
        this.getStrategySubmenu = function (specId, value) {
            if (this.StrategyMap[specId] == null) {
                return null
            } else {
                for (var key in this.StrategyMap[specId].map) {
                    if (this.StrategyMap[specId].map[key][value]) {
                        return key;
                    }
                }
            }
            return null;
        };

        //获取分类列表
        this.getCategory = function () {
            var arr = [], key;
            for (key in this.SpecMap) {
                arr.push(key);
            }
            for (key in this.StrategyMap) {
                arr.push(key);
            }

            return arr;
        };

        //凭skuId获取策略规格的值
        this.getCategoryIdbySkuId = function (skuid) {
            var that = this;
            for (var sku in this.data) {
                console.log(this.data[sku].id, skuid);
                if (this.data[sku].id == skuid) {
                    sku = sku.split('>').slice(1);
                    var res = {
                        spec: {},
                        strategy: {}
                    };
                    $.map(this.rank.split('>').slice(1), function (v, i) {
                        if (that.StrategyMap[v]) {
                            res.strategy[v] = sku[i];
                        } else {
                            res.spec[v] = sku[i];
                        }
                        return v;
                    });
                    return res;
                }
            }
            return null;

        };

        //根据传入Map，返回各规格的可选部分
        this.filter = function (options) {
            var res = {};
            var Reg_catch = '>([^>|]+)';
            var Reg_uncatch = '>(?:[^>|]+)';
            var Regs = {};
            var key, i, j;

            //获取所有路径
            var Search = (function () {
                var str = '';
                for (key in this.data) {
                    str += key + '|';
                }
                return str;
            }).bind(this)();

            //获取所有维度ID，构造返回信息
            var cateArr = (function () {
                return $.map(this.rank.slice(1).split('>'), function (v) {
                    res[v] = [];
                    return {
                        key: v,
                        value: false
                    }
                });
            }).bind(this)();

            //判断哪些维度在筛选条件中
            for (i = 0; i < cateArr.length; i++) {
                cateArr[i].value = options[cateArr[i].key] || false;
            }

            //构造RegExp
            for (i = 0; i < cateArr.length; i++) {
                Regs[cateArr[i].key] = '';

                for (j = 0; j < cateArr.length; j++) {

                    if (i == j) {
                        Regs[cateArr[i].key] += Reg_catch;
                    } else if (cateArr[j].value) {
                        Regs[cateArr[i].key] += '>' + cateArr[j].value;
                    } else {
                        Regs[cateArr[i].key] += Reg_uncatch;
                    }
                }

                Regs[cateArr[i].key] = new RegExp(Regs[cateArr[i].key], 'g');
            }

            for (key in Regs) {
                Search.replace(Regs[key], function (match, drag, index) {
                    res[key].push(drag);
                })
            }

            return res;
        };

        return this;
    }

    //分析规格，建立规格与SKU的关联表
    var analyse = function (SKUs, relative, strategyList) {
        //================ SKUs ===================
        //
        //      sku_id      String      SKU_Id
        //
        //      SpecId_A    Object
        //      ============= SpecId_A ============
        //      |
        //      |    id       String     SpecValueId
        //      |    value    String     SpecValueName
        //      |
        //      ------------------------------------
        //
        //      SpecId_Xs ... (结构同上)
        //
        //------------------------------------------

        //================ relative ================
        //
        //      Array
        //          [
        //
        //          ============= Objects ============
        //          |
        //          |    key       String     SpecId
        //          |    name      String     SpecName
        //          |
        //          ------------------------------------
        //          ...
        //
        //          ]
        //
        //------------------------------------------

        //================ strategyList ================
        //
        //      Array
        //          [
        //
        //          ============= Objects ============
        //          |
        //          |    strategy_type  Number     策略标识
        //          |    spec_id        String     SpecId
        //          |    list           Array      SpecList
        //          |
        //          ------------------------------------
        //          ...
        //
        //          ]
        //
        //------------------------------------------

        //  SKUs,   relative,   strategyList

        var SpecsManager = new Constructor_SpecsManager();
        strategyList = strategyList || [];
        var Strategy, SKU, i, j, key, SpecId, SpecValueId, SpecValueName, temp, key2, rankStr;

        //初步构造StrategyMap
        for (i = 0; i < strategyList.length; i++) {
            Strategy = strategyList[i];
            SpecsManager.StrategyMap[Strategy.spec_id] = {
                _id: Strategy.spec_id,
                strategy: Strategy.strategy_type,
                name: '',
                map: Strategy.list,
                all: {}
            };
            for (key in Strategy.list) {
                for (key2 in Strategy.list[key]) {
                    SpecsManager.StrategyMap[Strategy.spec_id].all[key2] = Strategy.list[key][key2];
                }
            }
        }

        //构造rank,添加无策略规格到SpecMap
        for (i = 0; i < relative.length; i++) {
            SpecsManager.rank += '>' + relative[i].key;
            if (SpecsManager.StrategyMap[relative[i].key]) {
                SpecsManager.StrategyMap[relative[i].key].name = relative[i].name;
            } else {
                SpecsManager.SpecMap[relative[i].key] = {
                    _id: relative[i].key,
                    name: relative[i].name,
                    map: {}
                };
            }
        }

        //补全SpecMap，存储SKU
        for (i = 0; i < SKUs.length; i++) {
            SKU = SKUs[i];
            temp = {
                id: SKU.sku_id
            };

            for (j = 0; j < relative.length; j++) {
                SpecId = relative[j].key;
                SpecValueId = SKU[SpecId].id;
                SpecValueName = SKU[SpecId].value;
                //若不在策略中，则添加到SpecMap
                if (!SpecsManager.StrategyMap[SpecId]) {
                    SpecsManager.SpecMap[SpecId].map[SpecValueId] = SpecValueName;
                }

                temp[SpecId] = SpecValueId;
                //SKU[key] = SKU[key].id;
            }
            SpecsManager.data[params2key(SpecsManager.rank, temp)] = temp;
        }

        //清除StrategyMap中的未使用部分
        //PS:服务器已经做了
        return SpecsManager;
    };

    var subtemplate = {};//子模版
    //通过division标识把可复用的部分模版提取出来
    page = page.replace(/\{\{division "(.+?)"}}([\s\S]+?)\{\{\/division}}/g, function (origin, id, tmp, index) {
        subtemplate[id] = template.compile(tmp);
        return tmp;
    });
    var render = template.compile(page);//主模版

    var apiList = {
        getInfo: api + 'commoditypage',
        addCart: api + 'cart/add'
    };

    var filter = {};//过滤器
    var bool_footer_isExpend = false;//类别选择是否展开
    var symbol = {};//symbol，用添加标志位

    window.vm = new Page.creat({
        $id: 'productDetail',
        $model: {
            data: {},
            $: {},
            sku: {},
            skus: [],
            count: 0,
            getInfo: function (id) {
                //初始化方法
                vm.$init({
                    setTitle: '商品详情'//todo 也许会改？
                });

                //预渲染
                $('#page').html(render({
                    label: [],
                    description: [],
                    brand: '',
                    price: 0,
                    price_cost: 0,
                    title: '',
                    pic: '',
                    SpecsManager: null
                }));

                //重置
                filter = {};
                bool_footer_isExpend = false;

                //$.ajax({
                //    url: '../testData/commoditypage.json',
                ex.jsonp({
                    url: apiList.getInfo,
                    data: {
                        _id: id
                    },
                    success: function (obj) {
                        if (!vm.isThisPage())return;
                        console.log(obj);
                        if (obj.code != 0)return '';//todo 跳到错误页去!
                        obj = obj.data;

                        var SpecsManager = analyse(obj.specs, obj.relative, obj.strategylist);
                        vm.skus = obj.skus;
                        var sku = vm.action.getSKUbyId(id);
                        if (sku == null) {
                            //todo 跳到错误页去!
                            throw '该商品已下架!';
                        }
                        vm.sku = sku;
                        vm.data = {
                            title: sku.title,
                            pic: sku.pic || [],
                            label: sku.label || [],
                            description: sku.description || [],

                            brand: sku.brand,
                            place: sku.place,
                            supplier: sku.supplier,

                            price: sku.price,
                            time_kill: sku.time_kill || '',
                            price_cost: sku.price_cost || 0,

                            stock: +sku.stock,
                            SpecsManager: SpecsManager
                        };

                        $('#page').html(render(vm.data));

                        $.map(SpecsManager.getCategory(), function (v, i) {
                            filter[v] = null;
                        });

                        ex.async(function () {

                            vm.bindEvent(vm.event);
                            vm.bind$(vm.$);

                            vm.$.cover.find('img').width(db.w).height(db.w);
                            vm.$.cover.find('.slider').width(db.w * sku.pic.length);
                            new IScroll('.cover', {
                                snap: true,
                                scrollX: true,
                                scrollY: false
                            });

                            $('.tag-timer').each(function () {
                                var $this = $(this);
                                var start = $this.attr('data-time');

                                var id = timer.register($this, function (time) {
                                    var t = start - (time - this.creatTime);
                                    if (t < 0) {
                                        timer.logout(id);
                                        this.$dom.find('span').html('已过期');
                                    } else {
                                        this.$dom.find('span').html(template.compile("{{t | formatTime:'hh:mm:ss'}}")({t: t}))
                                    }
                                })
                            });

                            //false:默认返回顶部
                            vm.getLastPosition(false);

                            //模拟分类选择
                            if (sku != null) {

                                var cate = SpecsManager.getCategoryIdbySkuId(sku._id);

                                //有库存时，初始的1购买量
                                if (sku.stock > 1) {
                                    vm.event.changeNumber(1);
                                }

                                //设置策略规格的一级分类
                                for (var key in cate.strategy) {
                                    if (cate.strategy) {
                                        $('[data-value="' + SpecsManager.getStrategySubmenu(key, cate.strategy[key]) + '"]').trigger('tapone');
                                    }
                                }

                                //异步，设置所有规格
                                ex.async(function () {
                                    for (var key in cate.spec) {
                                        $('[data-tag="' + key + '>' + cate.spec[key] + '"]').trigger('tapone');
                                    }
                                    for (var key in cate.strategy) {
                                        $('[data-tag="' + key + '>' + cate.strategy[key] + '"]').trigger('tapone');
                                    }
                                })

                            }

                        });
                    }
                })
            },
            event: {
                goto_cart: function () {
                    if (logger.isLogin) {
                        location.hash = '#/cart';
                    } else {
                        logger.login({
                            close: true,
                            callback: function () {
                                AddtoCart();
                            }
                        })
                    }
                },

                clickfb: function () {
                    if ($(this).hasClass('un'))return;

                    if (bool_footer_isExpend) {
                        //确认流程
                        var AddtoCart = function () {

                            if (symbol.addCarting)return;
                            symbol.addCarting = true;

                            ex.jsonp({
                                url: apiList.addCart,
                                method: "POST",
                                data: {
                                    sku_id: vm.sku._id,
                                    quantity: vm.count
                                },
                                success: function (res) {
                                    if (!vm.isThisPage())return;
                                    symbol.addCarting = false;
                                    if (res.code != 0) return layer.tips(res.msg);

                                    res = res.data || {};
                                    layer.tips('加入成功！');
                                    vm.event.closeShade();
                                    anime.cartAdd({
                                        cart: vm.$.cart,
                                        product: vm.$.product,
                                        callback: function () {
                                            vm.$.cart.find('div').text(res.count || 1).show();
                                        }
                                    });
                                },
                                error: function () {
                                    symbol.addCarting = false;
                                }
                            });
                        };

                        if (logger.isLogin) {
                            AddtoCart();
                        } else {
                            logger.login({
                                close: true,
                                callback: function () {
                                    AddtoCart();
                                }
                            })
                        }

                    } else {
                        //筛选流程
                        bool_footer_isExpend = true;
                        vm.$.float.show();
                        ex.async(function () {
                            vm.$.shade.css({opacity: 1});
                            vm.$.body.css({bottom: 0});
                        });
                        vm.action.checkFBStatus();
                    }
                },
                closeShade: function () {
                    if (symbol.closeShade)return;
                    symbol.closeShade = true;
                    vm.$.shade.css({opacity: 0});
                    vm.$.body.css({bottom: -999});
                    ex.async(function () {
                        vm.$.float.hide();
                        symbol.closeShade = false;
                        bool_footer_isExpend = false;
                        vm.action.checkFBStatus();
                    }, 300);
                },
                clickColorTag: function (specId) {
                    $(this).parent().find('.category-tag').removeClass('select');
                    $(this).addClass('select');
                    var type = $(this).attr('data-value');

                    filter[specId] = null;
                    var $cs = $('.category-strategy').html(subtemplate.StrategyArea({
                        map: vm.data.SpecsManager.StrategyMap[specId].map[type],
                        key: vm.data.SpecsManager.StrategyMap[specId]._id
                    }));

                    vm.bindEvent(vm.event, $cs);
                    vm.action.checkFilter(filter);
                    vm.action.changSKU();
                    vm.action.checkFBStatus();

                },
                clickTag: function () {
                    if ($(this).hasClass('un'))return;
                    var str = $(this).attr('data-tag').split('>');
                    var key = str[0];
                    var value_id = str[1];
                    filter[key] = value_id;
                    vm.action.checkFilter(filter);
                    vm.action.changSKU();
                    vm.action.checkFBStatus();

                    $(this).parent().find('.category-tag').removeClass('select');
                    $(this).addClass('select');

                },
                setCount: function () {

                    var $this = vm.$.count;
                    var count = +$this.val();
                    vm.action.setCount(count);
                    vm.action.checkFBStatus();

                },
                changeNumber: function (dt) {

                    vm.action.setCount(vm.count + (+dt));
                    vm.action.checkFBStatus();

                },
                clearFilter: function () {

                    for (var key in filter) {
                        filter[key] = null;
                    }
                    vm.action.changSKU();
                    vm.action.checkFBStatus();
                    $('[data-tag]').removeClass('un');
                    $('[data-tag]').removeClass('select');
                    $('[data-color]').removeClass('select');
                }
            },
            action: {
                setFooterPrice: function () {
                    vm.$.fp.html('<span>{{price}}</span>'.replace('{{price}}', vm.count * vm.sku.price / 10 + ''));
                },
                getSKUbyId: function (id) {
                    for (var i = 0; i < vm.skus.length; i++) {
                        if (vm.skus[i]._id == id) {
                            return vm.skus[i];
                        }
                    }

                    return null;
                },
                checkFilter: function (filter) {
                    var Filter_Result = vm.data.SpecsManager.filter(filter);
                    var i;

                    $('[data-tag]').addClass('un');
                    for (var key in Filter_Result) {
                        for (i = 0; i < Filter_Result[key].length; i++) {
                            $('[data-tag="' + key + '>' + Filter_Result[key][i] + '"]').removeClass('un');
                        }
                    }
                },
                changSKU: function () {
                    var id = vm.data.SpecsManager.getSKUid(filter);
                    var sku = vm.action.getSKUbyId(id);

                    if (sku) {
                        var $cp = $('[i-dom="product"]');
                        vm.sku = sku;
                        vm.$.product.html(subtemplate['product']({
                                label: sku.label || [],
                                price: sku.price,
                                price_cost: sku.price_cost || 0,
                                title: sku.title,
                                pic: sku.pic || [],
                                stock: +sku.stock
                            })
                        );
                        vm.bindEvent(vm.event, $cp);
                        vm.bind$(vm.$, $cp);
                        vm.action.setCount();
                    } else {
                        vm.$.product.html('');
                    }
                },
                setCount: function (val) {
                    var $this = vm.$.count;

                    val = isNaN(val) ? 1 : val;

                    if (isNaN(val) || val < 0) {
                        val = 0;
                    }
                    if (val > vm.data.stock) {
                        val = vm.data.stock;
                    }
                    vm.count = val;
                    $this.val(val);
                    vm.action.setFooterPrice();

                },
                checkFBStatus: function () {
                    var id = vm.data.SpecsManager.getSKUid(filter);
                    var $b = vm.$.fbutton;

                    if (bool_footer_isExpend) {
                        $b.text('确定');
                    } else {
                        $b.text('加入购物车');
                    }
                    if (bool_footer_isExpend && id == null || vm.count == 0) {
                        $b.addClass('un');
                    } else {
                        $b.removeClass('un');
                    }
                }
            }
        }
    });

    return {
        init: function (params) {

            vm.getInfo(params.id);
        }
    }
});